package cloud.xiangyixiang.www.spring.boot.java.basics.handler;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * <p>
 * ProxyInvocationHandler
 * </p>
 *
 * @author weixin
 * @date 2023/9/11 16:01
 */
public class ProxyInvocationHandler implements InvocationHandler {

    private Object target;

    public Object getTarget() {
        return target;
    }

    public void setTarget(Object target) {
        this.target = target;
    }

    /**
     * 生成得到代理类
     * @return {@link Object}
     */
    public Object getProxy() {
        return Proxy.newProxyInstance(this.getClass().getClassLoader(), target.getClass().getInterfaces(),this);
    }

    /**
     * 处理代理实例，并返回结果
     * @param proxy {@link Object}
     * @param method {@link Method}
     * @param args {@link Object[]}
     * @return {@link Object}
     */
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        log(method.getName());
        //动态代理的本质就是使用反射机制来实现
        return method.invoke(target, args);
    }

    /**
     * 记录
     * @param msg {@link String}
     */
    public void log(String msg) {
        System.out.println("执行了" + msg + "方法");
    }
}
